<template>
  <div>
    <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
      <template #id="{ row }">
        <vxe-input v-model="row.id" />
      </template>
      <template #state="{ row }">
         <!-- <vxe-input v-model="row.state" /> -->
        <el-tag type="primary" v-if="row.state == 0">{{ formatStatus(row.state) }}</el-tag>
        <el-tag type="success" v-if="row.state == 1">{{ formatStatus(row.state) }}</el-tag>
      </template>
      <template #user_owner_id="{ row }">
        <vxe-input v-model="row.user_owner_id" />
      </template>
      <template #user_id="{ row }">
        <vxe-input v-model="row.user_id" />
      </template>
      <template #rmb="{ row }">
        <vxe-input v-model="row.rmb" />
      </template>
      <template #image="{ row }">
        <!-- <vxe-input v-model="row.image" /> -->
        <el-upload
          class="avatar-uploader"
          action
          :http-request="(params)=>httpRequest(params,row)"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <el-image style="width: 50px; height: 50px" :src="row.image" :fit="fit" />
        </el-upload>
      </template>
      <template #number="{ row }">
        <vxe-input v-model="row.number" />
      </template>
      <template #pager>
        <!--使用 pager 插槽-->
        <vxe-pager
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total',
          ]"
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :total="tablePage.total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import VXETable from 'vxe-table'
  import { getHouseList, insertHouse, updateHouse, deleteHouse } from '/@/api/house/house.ts'
  import { createLocalStorage } from '/@/utils/cache'
  import { LOCALE_KEY } from '/@/enums/cacheEnum'
  import { useUserStore } from '/@/store/modules/user'
  import { upload } from '/@/api/person/person.ts'
  import { RoleEnum } from '/@/enums/roleEnum'

  const imageUrl = ref('')
  const userStore = useUserStore()
  const customHeaders = reactive({
    'Content-Type': 'multipart/form-data',
  })
  const ls = createLocalStorage()
  const userInfo = ls.get(LOCALE_KEY+'bb_user_info')
  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const imageType = reactive({
    user_id: userStore.getUserInfo.uid,
    tid: 2,
    info: '用户',
  })
  const data = reactive({
    imageType: JSON.stringify(imageType),
  })
  const defaultCulums = reactive([
    { type: 'checkbox', width: 50 },
    { type: 'seq', width: 60 },
    { field: 'id', title: '编号', slots: { edit: 'id' } },
    { field: 'state', title: '状态', slots: {default: 'state', edit: 'state' } },
    {
      field: 'user_owner_id',
      title: '房主',
      slots: { edit: 'user_owner_id' },
    },
    { field: 'user_id', title: '用户', slots: { edit: 'user_id' } },
    { field: 'rmb', title: '价格', editRender: {}, slots: { edit: 'rmb' } },
    { field: 'image', title: '图片详情',editRender: {}, slots: {default: 'image', edit: 'image' } },
    { field: 'number', title: '可住人数',editRender: {}, slots: { edit: 'number' } },
  ])
  const validRules = ref({
    rmb: [{ required: true, message: '请输入价格' }],
    image: [{ required: true, message: '请上传图片' }],
    number: [{ required: true, message: '请输入可住人数' }],
  })
  const xGrid = ref()
  let gridOptions = reactive({
    border: true,
    keepSource: true,
    id: 'toolbar_demo_1',
    height: 530,
    editRules: validRules,
    printConfig: {},
    importConfig: {},
    exportConfig: {},
    columnConfig: {
      resizable: true,
    },
    customConfig: {
      storage: true,
    },
    editConfig: {
      trigger: 'click',
      mode: 'row',
      showStatus: true,
    },
    columns: defaultCulums,
    toolbarConfig: {
      buttons: [
        { code: 'myDelete', name: '删除' },
        { code: 'mySave', name: '保存', status: 'success' },
        { code: 'myExport', name: '导出数据', type: 'text', status: 'warning' },
      ],
      tools: [{ code: 'myPrint', name: '自定义打印' }],
      import: true,
      export: true,
      print: true,
      zoom: true,
      custom: true,
    },
    data: [
      {
        id: 376,
        uid: '24',
        name: '24',
        password: '24',
        type: 2,
        image: '24',
        rmb: 24,
        create_time: '2023-12-31 23:10:38',
      },
    ],
  })
  const gridEvents = {
    async toolbarButtonClick({ code }) {
      const $grid = xGrid.value
      if ($grid) {
        switch (code) {
          case 'myInsert': {
            $grid.insert({user_owner_id:userInfo.uid})
            break
          }
          case 'myDelete': {
            $grid.removeCheckboxRow()
            break
          }
          case 'mySave': {
            const $table = xGrid.value
            if ($table) {
              const errMap = await $table.validate()
              if (errMap) {
                VXETable.modal.message({ status: 'error', message: '校验不通过！' })
                return
              } else {
                VXETable.modal.message({ status: 'success', message: '校验成功！' })
              }
            }
            const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
            const promise = []
            if (insertRecords.length > 0) {
              const promise1 = insertHouse(insertRecords).then((res) => {})
              promise.push(promise1)
            }
            if (removeRecords.length > 0) {
              const promise2 = deleteHouse(removeRecords).then((res) => {})
              promise.push(promise2)
            }
            if (updateRecords.length > 0) {
              const promise3 = updateHouse(updateRecords).then((res) => {})
              promise.push(promise3)
            }

            Promise.allSettled(promise).then(() => {
              getData()
              VXETable.modal.message({
                content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`,
                status: 'success',
              })
            })
            break
          }
          case 'myExport': {
            $grid.exportData({
              type: 'csv',
            })
            break
          }
        }
      }
    },
    toolbarToolClick({ code }) {
      const $grid = xGrid.value
      if ($grid) {
        switch (code) {
          case 'myPrint': {
            $grid.print()
            break
          }
        }
      }
    },
  }

  const isUser = userInfo.roles.find((item) => item.value == RoleEnum.User)
  const isSuperManager = userInfo.roles.find((item) => item.value == RoleEnum.SuperManager)
  const isHouseManager = userInfo.roles.find((item) => item.value == RoleEnum.HouseManager)
  if (isHouseManager) {
    gridOptions.toolbarConfig.buttons = [
        { code: 'myInsert', name: '新增' },
        { code: 'myDelete', name: '删除' },
        { code: 'mySave', name: '保存', status: 'success' },
        { code: 'myExport', name: '导出数据', type: 'text', status: 'warning' },
    ]
  }

  onMounted(() => {
    getData()
  })

  const getData = () => {
    const data = {
      page: 0,
    }

    getHouseList(data).then((res) => {
      const data1 = res.msg
      gridOptions.data = data1
    })
  }

  const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
  }

  const validEvent = async () => {
    const $table = xGrid.value
    if ($table) {
      const errMap = await $table.validate()
      if (errMap) {
        VXETable.modal.message({ status: 'error', message: '校验不通过！' })
      } else {
        VXETable.modal.message({ status: 'success', message: '校验成功！' })
      }
    }
  }

    const formatStatus = (value) => {
    if (value == 0) {
      return '空闲'
    }
    if (value == 1) {
      return '已住'
    }
  }

  const httpRequest = (params,row) => {
    const form = new FormData()
    form.append('image', params.file)
    form.append('imageType', new Blob([data.imageType], { type: 'application/json' }))
    upload(form).then((res) => {
      row.image = res.msg;
    })
  }

  const handleAvatarSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
  }
</script>

<style lang="scss" scoped>
  :deep(.vxe-table--body-wrapper){
    height: 500px !important;
  }
</style>
